from imaplib import *
import sys
import string
import time
import os

if ( os.name == 'nt' ):
	import strptime
	time.strptime = strptime.strptime
	del strptime

username = sys.argv[1]
password = sys.argv[2]
output = sys.argv[3]
message = open(output, 'w')

server = IMAP4_SSL("imap.gmail.com", 993)
server.login(username, password)

server.select("Python Imap")

folder_status = server.fetch( '1:*', '(UID ENVELOPE)')

time_list = list()
full_list = list()
x = 0

while ( x != len(folder_status[1]) ):
	number_status =  folder_status[1][x].split(" ")[0] 
	message_status =  folder_status[1][x].split(", ")[1].split("-")[0] 
	zone_status = folder_status[1][x].split(",",1)[1].split(" ",1)[1].split(" ",1)[1].split(" ",1)[1].split(" ",1)[1].split(" ",1)[1].split("(",1)[1].split(")",1)[0]
	args = "%d %b %Y %H:%M:%S "
	number_sort = number_status
	if ( (len(zone_status) == 3)&(os.name != 'nt') ):
		args = args + "%Z"
	else:
		zone_status = ""	
	print number_status + ": " + message_status + zone_status
	time_sort = message_status + zone_status
	full_list.append( time.strptime(time_sort, args))
	if ( folder_status[1][x].find("SyncFox") != -1 ): 
		time_list.append( time.strptime(time_sort, args))
	x = x + 1

time_list.sort()
time_list.reverse()
num = full_list.index( time_list[0] ) + 1

print num


# Returns a damn tuple
data = server.fetch(num, '(UID BODY[TEXT])')

# Assign the message data of the tupple to the string
# [1] is the list of the ( 'OK', *tuple* of message parts ) tupple returned by fetch
# which selects the tuple of message parts
# [0] Selects the first part of the *tuple* of message parts which is a list
# The last [1] selects the first part of the list which is a string of the message
data_string = data[1][0][1]

# Takes the string of the entire message, sans headers, and first partitions
# @ 'base64' returning a tupple of before partition, partition, after
# [2] takes after string, in this case attachment, and partitions that to
# attachment and partition, which is the last separator
# [0] returns only the string of the attachment from the final partition
# to the attachment_64 variable
attachment_64 = data_string.split("base64",1)[1].split('--FIN--',1)[0].strip()

if ( os.name == 'nt' ):
	temp = open('temp', 'w')
	temp.write(attachment_64)
	temp.close()
	base64 = os.popen("base64.exe" + " -d " + 'temp' + " " + "\"" + output + "\"")
	base64.close()
	os.remove('temp')
else:
	import base64
	attachment = base64.decodestring(attachment_64)
	message.write(attachment)
	message.close()
